// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import * as fs from 'fs-extra';
import * as path from 'path';
import clipboard from 'clipboardy';

import { OdooMisc } from './odoo_misc';
import { exists } from 'fs';

async function commonInputBox(placeHolder: string, prompt?: string) {
	return vscode.window.showInputBox({
		prompt,
		placeHolder,
		valueSelection: [-1, -1],
		validateInput: (text) => {
			if (!text) {
				return '输入的内容不能为空';
			}
			// 返回null/undefined代表通过
			return undefined;
		}
	});
}

function capitalizeFirstLetter(word: String) {
	return   word.charAt(0).toUpperCase() + word.slice(1)
}

export function activate(context: vscode.ExtensionContext) {
	const odooMisc = new OdooMisc(context);

	let createModule = vscode.commands.registerCommand('odoo-misc-plugin.createModule', (uri) => {
		fs.stat(uri.fsPath, async (err: any, stats: { isFile: () => any; }) => {
			if (stats.isFile()) {
				vscode.window.showErrorMessage('无法创建项目，选择的是文件');
				return;
			}
			const name = await commonInputBox('请输入模块名称');
			if(name) {
				const odooVersion = await vscode.window.showQuickPick(
					[ '14', '15', '16'],
					{ placeHolder: '选择Odoo版本'}
				);
				if(odooVersion) {
					const hasWebModule = await vscode.window.showQuickPick(
						['是', '否'],
						{ placeHolder: '是否包含前端内容' }
					);
					if(hasWebModule) {
						odooMisc.createModule({ name , destDir: uri.fsPath, odooVersion,  hasWebModule});
					}
				}
			}
		});
	});
	let createNewModel = vscode.commands.registerCommand('odoo-misc-plugin.createNewModel', (uri) => {
		const manifestPath = path.join(uri.fsPath, '__manifest__.py');
		fs.stat(manifestPath, (err: any, stats: { isFile: () => any; }) => {
			if (stats && stats.isFile()) {
				commonInputBox('请输入模型名称').then((name) => {
					if(name) {
						odooMisc.createNewModel(name, uri.fsPath);
					}
				});
			} else {
				vscode.window.showErrorMessage('创建模型失败，请选择odoo模块目录进行创建');
			}
		});
	});

	let createInheritModel = vscode.commands.registerCommand('odoo-misc-plugin.createInheritModel', (uri) => {
		const manifestPath = path.join(uri.fsPath, '__manifest__.py');
		fs.stat(manifestPath, (err: any, stats: { isFile: () => any; }) => {
			if (stats && stats.isFile()) {
				commonInputBox('请输入被继承的模型的名称').then((name) => {
					if(name) {
						odooMisc.createInheritModel(name, uri.fsPath);
					}
				});
			} else {
				vscode.window.showErrorMessage('创建继承模型失败，请选择odoo模块目录进行创建');
			}
		});
	});

	let createComponent = vscode.commands.registerCommand('odoo-misc-plugin.createComponent', (uri) => {
		const manifestPath = path.join(uri.fsPath, '__manifest__.py');
		fs.stat(manifestPath, async (err: any, stats: { isFile: () => any; }) => {
			if (stats && stats.isFile()) {
				const name = await commonInputBox('请输入组件名称，如果名称包含多个单词，使用空格分割');
				if(name) {
					const componentType = await vscode.window.showQuickPick(
						[ 'field', 'action', 'common'],
						{ placeHolder: '请选择组件类型，会根据组件类型设置不同的js文件模板'}
					);
					if(componentType) {
						let words: string[] = [];
						const names = name.split(' ');
						names.forEach((word) => {
							words.push(capitalizeFirstLetter(word));
						});
						const componentName = words.join('');
						const filenName = names.join('_');
						odooMisc.createComponent(componentName, filenName, componentType, uri.fsPath);
					}
				}
			} else {
				vscode.window.showErrorMessage('创建组件失败，请选择odoo模块目录进行创建');
			}
		});
	});

	let createService = vscode.commands.registerCommand('odoo-misc-plugin.createService', (uri) => {
		const manifestPath = path.join(uri.fsPath, '__manifest__.py');
		fs.stat(manifestPath, async (err: any, stats: { isFile: () => any; }) => {
			if (stats && stats.isFile()) {
				const name = await commonInputBox('请输入服务名称，如果名称包含多个单词，使用空格分割');
				if(name) {
					let words: string[] = [];
					const names = name.split(' ');
					names.forEach((word, index) => {
						if(index === 0) {
							words.push(word)
						} else {
							words.push(capitalizeFirstLetter(word));
						}
					});
					const serviceName = words.join('');
					const filenName = names.join('_');
					odooMisc.createService(serviceName, filenName, uri.fsPath);
				}
			} else {
				vscode.window.showErrorMessage('创建服务失败，请选择odoo模块目录进行创建');
			}
		});
	});

	let getImportPath = vscode.commands.registerCommand('odoo-misc-plugin.getImportPath', async (uri) => {
		const staticPath = 'static/src/'
		const pathNames = uri.fsPath.replace('.js', '').split(path.sep).slice(1)
		const staticIndex = pathNames.findIndex((element: string) => element==='static')
		const importPath = `import {  } from "${'@'+pathNames.slice(staticIndex-1).join('/').replace(staticPath, '')}";`
		await clipboard.write(importPath);
	});

	let openImportFile = vscode.commands.registerCommand('odoo-misc-plugin.openImportFile', async (uri) => {
		const addonPaths = vscode.workspace.getConfiguration('odoo-misc-plugin').get('odoo-addon-paths')
		if(Array.isArray(addonPaths) && addonPaths.length) {
			const editor = vscode.window.activeTextEditor;
			if(editor) {
				const selectionContent = editor.document.getText(editor.selection)
				let importPath = selectionContent.match(/(\'|\")@.*?(\'|\")/g)
				if(importPath) {
					const _path = importPath[0].slice(2, -1)
					let jsFilePath = ''
					if(_path === 'odoo/owl') {
						jsFilePath = path.join('web', 'static', 'lib', 'owl', 'owl.js')
					} else {
						const moduleName = _path.split("/", 1)[0]
						jsFilePath = _path.replace(moduleName, moduleName + '/static/src')+'.js'
						// 兼容平台的路径
						jsFilePath = jsFilePath.split("/").join(path.sep)
					}
					addonPaths.forEach(async (p) => {
						const absPath = path.join(p, jsFilePath)
						if(await fs.pathExists(absPath)) {
							let fileUri = vscode.Uri.file(absPath)

							const doc = await vscode.workspace.openTextDocument(fileUri);
							vscode.window.showTextDocument(doc, {
								preview: false,
								viewColumn: vscode.ViewColumn.Active
							});
							return
						} else {
							vscode.window.showErrorMessage(`未找到导入文件：${absPath}`);
						}
					})
				}
			}
		} else {
			vscode.window.showErrorMessage('没有配置Odoo模块路径');
		}
	});
	context.subscriptions.push(
		createModule,
		createNewModel,
		createInheritModel,
		createComponent,
		createService,
		getImportPath,
		openImportFile
	);
}

// this method is called when your extension is deactivated
export function deactivate() { }
